package com.technology.education.ui.common.manage_account

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.provider.UserDictionary.Words.APP_ID
import android.view.Gravity
import android.widget.ImageView
import com.angcyo.dsladapter.dslItem
import com.angcyo.dsladapter.updateItem
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.technology.education.R
import com.technology.education.base.BaseRecyclerTopBarFragment
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.data.model.UserInfoModel
import com.technology.education.dslitem.ItemColumnTitleText
import com.technology.education.dslitem.style.DrawableStyle
import com.technology.education.ext.*
import com.technology.education.ui.common.register.ActivityRegister
import com.technology.education.ui.common.role_selector.RoleSelectorActivity
import com.tencent.android.tpush.common.BroadcastAgent.registerReceiver
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.util.startActivity
import org.json.JSONObject
import java.lang.Exception


class ManageAccountFragment : BaseRecyclerTopBarFragment<ManageAccountViewModel>() {
    override fun initViews() {
        setTitle("账号管理")
    }

    override fun lazyLoadData() {
        regToWx()
    }

    // IWXAPI 是第三方app和微信通信的openApi接口
    private var api: IWXAPI? = null

    private fun regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(requireContext(), AppData.WX_ID)

        // 将应用的appId注册到微信
        api?.registerApp(AppData.WX_ID)
    }

    private fun upload(it: ArrayList<Photo>) {
        showLoading()
        getAppViewModel().upload(it) {
            if (it.isNotEmpty()) {
                mViewModel.updateHeader(it[0])
            }
        }
    }

    override fun createObserver() {
        getAppViewModel().userInfo.observe(this) {
            setUI(it)
        }
        observe(SpKeys.UPDATE_USER_AVATAR, String::class.java) {
            getAppViewModel().userInfo.value?.avatar = it
            renderAdapter {
                updateItem("header")
            }
        }

        mViewModel.bindResult.observe(this) {
            getAppViewModel().getInfo(onlyData = true)
            onBack()
        }

        observe(SpKeys.WX_INFO, String::class.java) {
            /**
             * {
            "openid": "OPENID",
            "nickname": "NICKNAME",
            "sex": 1,
            "province": "PROVINCE",
            "city": "CITY",
            "country": "COUNTRY",
            "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
            "privilege": ["PRIVILEGE1", "PRIVILEGE2"],
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
            }
             */
            try {
                val json = JSONObject(it)
                mViewModel.bindWx(
                    hashMapOf(
                        "avatar" to json.getString("headimgurl"),
                        "openid" to json.getString("openid"),
                        "nickname" to json.getString("nickname")
                    )
                )
            } catch (e: Exception) {
                toast("获取信息失败")
            }

        }
    }

    private fun setUI(info: UserInfoModel) {
        renderAdapter {
            clearItems()
            dslItem(R.layout.item_manage_header) {
                itemBindOverride = { itemHolder, _, _, _ ->
                    itemTag = "header"
                    itemBottomInsert = 1
                    itemDecorationColor = getColor(R.color.gray_light)
                    itemHolder.v<ImageView>(R.id.iv_header)?.apply {
                        header(info.avatar, this)
                    }
                    itemHolder.clickItem {
                        selectPhoto(selectedList = arrayListOf()) {
                            if (it.isNotEmpty()) {
                                upload(it)
                            }
                        }
                    }
                }
            }
            dslItem(
                ItemColumnTitleText(
                    "手机号",
                    content = info.mobile,
                    contentDrawable = DrawableStyle(rightDrawable = R.drawable.ic__arrow_right_gray_24)
                )
            ) {
                style.contentGravity = Gravity.RIGHT
                style.contentTextColor = R.color.gray_light
                style.contentTextSize = 14f
                style.titleTextSize = 14f
                itemClick = {
                    navigation(requireView(), R.id.action_manageAccount_to_bindWxFragment)
                }
            }
            dslItem(
                ItemColumnTitleText(
                    "绑定微信",
                    content = if (info.openid.isNullOrEmpty()) "未绑定" else "已绑定",
                    contentDrawable = DrawableStyle(rightDrawable = R.drawable.ic_baseline_keyboard_arrow_right_24)
                )
            ) {
                style.contentGravity = Gravity.RIGHT
                style.contentTextColor = R.color.gray_light
                style.contentTextSize = 14f
                style.titleTextSize = 14f
                itemClick = {
                    if (info.openid.isNullOrEmpty()) {
                        autoWx()
                    } else {
                        showToast("当前账号已绑定微信")
                    }
                }
            }
            dslItem(
                ItemColumnTitleText(
                    "密码设置",
                    content = "更改密码",
                    contentDrawable = DrawableStyle(rightDrawable = R.drawable.ic__arrow_right_gray_24)
                )
            ) {
                style.contentGravity = Gravity.RIGHT
                style.contentTextColor = R.color.gray_light
                style.contentTextSize = 14f
                style.titleTextSize = 14f
                itemClick = {
                    startActivity(ActivityRegister::class, Pair("type", 2))
                }
            }
            dslItem(
                ItemColumnTitleText(
                    "切换角色",
                    content = "",
                    contentDrawable = DrawableStyle(rightDrawable = R.drawable.ic__arrow_right_gray_24)
                )
            ) {
                style.contentGravity = Gravity.RIGHT
                style.contentTextColor = R.color.gray_light
                style.contentTextSize = 14f
                style.titleTextSize = 14f
                style.lineHeight = 1
                style.bottomOffset = 1
                itemBottomInsert = 1
                itemClick = {
                    logout()
                }
            }
        }
    }

    private fun autoWx() {
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = "wechat_sdk_demo_education"
        api?.sendReq(req)
    }
}